<template>
  <div class="shared-documents">
    <el-card class="shared-card">
      <template #header>
        <div class="card-header">
          <h2>共享文档</h2>
          <el-button type="primary" @click="handleShare">
            <el-icon><Share /></el-icon>分享文档
          </el-button>
        </div>
      </template>

      <el-table
        :data="sharedDocuments"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="title" label="文档名称">
          <template #default="{ row }">
            <div class="document-title">
              <el-icon :size="20" class="file-icon">
                <component :is="getFileIcon(row.file_type)" />
              </el-icon>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="file_type" label="类型" width="100" align="center" />
        <el-table-column prop="shared_by" label="分享者" width="120" align="center" />
        <el-table-column prop="share_time" label="分享时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.share_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleDownload(scope.row)">
              <el-icon><Download /></el-icon>下载
            </el-button>
            <el-button link type="danger" @click="handleUnshare(scope.row)">
              <el-icon><Delete /></el-icon>取消分享
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分享对话框 -->
    <el-dialog
      v-model="shareDialogVisible"
      title="分享文档"
      width="30%"
    >
      <el-form :model="shareForm" label-width="80px">
        <el-form-item label="选择文档">
          <el-select v-model="shareForm.documentId" placeholder="请选择文档">
            <el-option
              v-for="doc in myDocuments"
              :key="doc.id"
              :label="doc.title"
              :value="doc.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分享给">
          <el-select
            v-model="shareForm.users"
            multiple
            filterable
            placeholder="请选择用户"
          >
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShare">
            确认分享
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Share,
  Download,
  Delete,
  Document as DocIcon,
  Grid as ExcelIcon,
  Picture as PptIcon,
  DocumentCopy as PdfIcon,
  More as OtherIcon
} from '@element-plus/icons-vue'
import http from '../utils/axios'  // 使用配置好的axios实例

const API_BASE_URL = `${import.meta.env.VITE_API_URL}/api`
const loading = ref(false)
const sharedDocuments = ref([])
const myDocuments = ref([])
const users = ref([])
const shareDialogVisible = ref(false)
const shareForm = ref({
  documentId: '',
  users: []
})

// 获取共享文档列表
const fetchSharedDocuments = async () => {
  try {
    loading.value = true
    const response = await http.get('/documents/shared/')
    
    // 处理响应数据 - 支持两种格式：直接数组或带分页的对象
    if (Array.isArray(response.data)) {
      sharedDocuments.value = response.data
    } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
      // 返回带分页信息的对象
      sharedDocuments.value = response.data.results
    } else {
      // 如果返回的既不是数组也不是带results的对象，则设置为空数组
      console.warn('Unexpected response format:', response.data)
      sharedDocuments.value = []
    }
  } catch (error) {
    console.error('获取共享文档失败:', error)
    ElMessage.error('获取共享文档失败')
    sharedDocuments.value = [] // 确保在错误情况下也设置为数组
  } finally {
    loading.value = false
  }
}

// 获取我的文档列表
const fetchMyDocuments = async () => {
  try {
    const response = await http.get('/documents/')
    
    // 处理响应数据 - 支持两种格式：直接数组或带分页的对象
    if (Array.isArray(response.data)) {
      myDocuments.value = response.data
    } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
      // 返回带分页信息的对象
      myDocuments.value = response.data.results
    } else {
      // 如果返回的既不是数组也不是带results的对象，则设置为空数组
      console.warn('Unexpected response format:', response.data)
      myDocuments.value = []
    }
  } catch (error) {
    console.error('获取我的文档失败:', error)
    ElMessage.error('获取我的文档失败')
    myDocuments.value = [] // 确保在错误情况下也设置为数组
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await http.get('/users/')
    
    // 处理响应数据 - 支持两种格式：直接数组或带分页的对象
    if (Array.isArray(response.data)) {
      users.value = response.data
    } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
      // 返回带分页信息的对象
      users.value = response.data.results
    } else {
      // 如果返回的既不是数组也不是带results的对象，则设置为空数组
      console.warn('Unexpected response format:', response.data)
      users.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    users.value = [] // 确保在错误情况下也设置为数组
  }
}

const getFileIcon = (fileType) => {
  const type = fileType.toLowerCase()
  if (type === 'doc' || type === 'docx') return DocIcon
  if (type === 'xls' || type === 'xlsx') return ExcelIcon
  if (type === 'ppt' || type === 'pptx') return PptIcon
  if (type === 'pdf') return PdfIcon
  return OtherIcon
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const handleShare = async () => {
  await fetchMyDocuments()
  await fetchUsers()
  shareDialogVisible.value = true
}

const handleDownload = async (document) => {
  try {
    const response = await http.get(`/documents/${document.id}/download/`, {
      responseType: 'blob'
    })
    
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', document.title)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

const handleUnshare = async (document) => {
  try {
    await http.delete(`/documents/${document.id}/share/`)
    ElMessage.success('取消分享成功')
    fetchSharedDocuments()
  } catch (error) {
    console.error('取消分享失败:', error)
    ElMessage.error('取消分享失败')
  }
}

const confirmShare = async () => {
  if (!shareForm.value.documentId || shareForm.value.users.length === 0) {
    ElMessage.warning('请选择文档和用户')
    return
  }
  
  try {
    await http.post(`/documents/${shareForm.value.documentId}/share/`, {
      users: shareForm.value.users
    })
    ElMessage.success('分享成功')
    shareDialogVisible.value = false
    shareForm.value = {
      documentId: '',
      users: []
    }
    fetchSharedDocuments()
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}

onMounted(() => {
  fetchSharedDocuments()
})
</script>

<style scoped>
.shared-documents {
  max-width: 1200px;
  margin: 0 auto;
}

.shared-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.document-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 